package YAVMM::Server::Utils;
use warnings;
use strict;

use Dancer ':syntax';
load_app 'YAVMM';

use Dancer::Config;
Dancer::Config->load;

use YAVMM::Settings::MongoDB;
use YAVMM::HostDB;
use YAVMM::Host;

sub get_settings {
    if (not vars->{settings}) {
	my $settings = YAVMM::Settings::MongoDB->new(
	    'hostname'   => config->{mongo_host}          || 'localhost',
	    'port'       => config->{mongo_port}          || 27017,
	    'dbname'     => config->{mongo_db_name}       || 'yavmm',
	    'collection' => config->{settings_collection} || 'yavmm_settings',
	);

	var settings => $settings;
    }

    return vars->{settings};
}

sub get_hostdb {
    my $hostdb = YAVMM::HostDB->new(settings => get_settings);
    $hostdb->load_plugin('MongoDB');
    $hostdb->collection(config->{hosts_collection});

    var hostdb => $hostdb;

    return vars->{hostdb};
}

sub get_clusters {
    my $hostdb = get_hostdb;
    return $hostdb->get_clusters();
}

sub get_hosts {
    my @cluster = @_;

    my $hostdb = get_hostdb;

    my @hosts = ();

    @cluster = $hostdb->get_clusters() if not @cluster;

    #debug "Clusters: @cluster";

    foreach my $cluster (@cluster) {
	push @hosts, $hostdb->get_hosts($cluster);
    }

    return @hosts;
}

sub get_host {
    my $hostname = shift;

    return get_hostdb->get_host($hostname);
}

sub get_hoststatdb {
    if (not vars->{host_stat_db}) {
	my $db = YAVMM::HostStatDB->new(settings => get_settings);
	$db->load_plugin('MongoDB');
	$db->collection(config->{hoststats_collection});

	var host_stat_db => $db;
    }

    return vars->{host_stat_db};
}

sub get_clientstatdb {
    if (not vars->{client_stat_db}) {
	my $db = YAVMM::ClientStatDB->new(settings => get_settings);
	$db->load_plugin('MongoDB');
	$db->collection(config->{clientstats_collection});

	var host_stat_db => $db;
    }

    return vars->{host_stat_db};
}

1;
